<template>
  <tree-select
    ref="treeSelect"
    @treeSelect="handleSelect"
    @cancelSelect="handleCancelSelect"
    :placeholder="placeholder"
    :customLabel="true"
    :labelOnly="labelOnly"
    :disableBranchNodes="true"
    :selectStyle="selectStyle"
    :options="deptTreeData"
    :selectValue="value"
    :multiple="multiple"
    :disabled="disabled"
    :clearable="clearable"
    @valueChange="valueChange"
  />
</template>

<script>
// 引用组件监听 select 事件获得选择值
// 回显值 props 传selectValue
// 重置调用该组件的 reset 方法
import TreeSelect from '@/components/ETreeSelect'
import { schemeDeptUser } from '@/api/eval'

export default {
  name: 'DeptUserS',
  components: {
    TreeSelect
  },
  props: {
    labelOnly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: undefined
    },
    multiple: {
      type: Boolean,
      default() {
        return false
      }
    },
    selectValue: [String, Array], // 多选时为Array
    selectStyle: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  mounted() {
    schemeDeptUser().then(res => {
      const arr = res.data
      this.deptTreeData = this.handleData(arr)
    })
  },
  data() {
    return {
      deptTreeData: [],
      value: undefined
    }
  },
  watch: {
    selectValue(n, o) {
      if (n !== o) {
        this.value = n
      }
    }
  },
  created() {
    this.value = this.selectValue
  },
  methods: {
    handleData(arr, parent) {
      arr.map(v => {
        v.parentLabel = parent ? parent.label : ''
        v.childLabel = v.title
        v.id = v.key
        v.label = v.title
        v.customLabel = parent ? parent.title + '-' + v.title : v.title
        if (v.children && v.children.length > 0) {
          this.handleData(v.children, v)
        } else {
          if (v.key.split('-').length === 1) {
            v.isDisabled = true // 设置部门禁止选择
          }
          delete v.children
        }
      })
      return arr
    },
    reset() {
      this.$refs.treeSelect.reset()
    },
    handleSelect(node) {
      if (node.id.split('-').length === 1) {
        this.$nextTick(() => {
          this.reset()
        })
        this.$message.error('请选择人员')
        this.$emit('select', null)
        return false
      } else {
        this.$emit('select', node)
      }
    },
    handleCancelSelect(node) {
      console.log('node', node)

      this.$emit('cancelSelect', node)
    },
    valueChange(value, valueDetail) {
      this.$emit('valueChange', value, valueDetail)
    }
  }
}
</script>
